package ca.nfb.media.nfbPlayer.accessibility
{
	import ca.nfb.media.nfbPlayer.ComModule;
	
	import flash.accessibility.Accessibility;
	import flash.accessibility.AccessibilityProperties;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.events.TimerEvent;
	import flash.system.Capabilities;
	import flash.utils.Timer;
	
	public class ScreenReaderManager
	{
		public static var screenReaderElements	:Object = new Object();
		
		public var hasScreenReader			:Boolean = false;
		public var hasAccessibility			:Boolean = false;
		public var checkTimer				:Timer = new Timer(2500, 1);
		public var isChecking				:Boolean = false;
		public var queuedAccesses			:Array = new Array();
		
		public function ScreenReaderManager()
		{
			if (Capabilities.hasAccessibility)
			{
				checkForScreenReader();
				hasAccessibility = true;
			}
			else
			{
				hasScreenReader = false;
				hasAccessibility = false;
			}
			checkTimer.addEventListener(TimerEvent.TIMER_COMPLETE, checkDone, false, 0, true);
		}
		
		private function toggleAccess(displayObject:DisplayObject):void
		{
			if (hasScreenReader)
			{
				var accessProps:AccessibilityProperties = new AccessibilityProperties();
				accessProps.name = ScreenReaderManager.getLabel(displayObject.name);
				displayObject.accessibilityProperties = accessProps;
				Accessibility.updateProperties();
			}
			else
			{
				if (isChecking)
					queuedAccesses.push({displayObject:displayObject});
			}
		}
		
		public function addAccess(displayObject:DisplayObject, en:String, fr:String):void
		{
			ScreenReaderManager.addScreenReaderElement(displayObject.name, en, fr);
			toggleAccess(displayObject);
		}
		
		private function checkForScreenReader():void
		{
			isChecking = true;
			checkTimer.start();	
		}
		
		private function checkDone(evt:TimerEvent):void
		{
			isChecking = false;
			
			if (Accessibility.active)
				hasScreenReader = true;
			
			if (queuedAccesses.length > 0)
				parseQueue();		
		}
		
		private function parseQueue():void
		{
			for (var i:Number=0; i<queuedAccesses.length; ++i)
				this.toggleAccess(queuedAccesses[i].displayObject);
			
			queuedAccesses = new Array();
		}
		
		public static function addScreenReaderElement(key:String, englishLabel:String="", frenchLabel:String=""):void
		{
			screenReaderElements[key] = {en:englishLabel, fr:frenchLabel};
		}
		
		public static function getLabel(label:String):String
		{
			if (screenReaderElements[label])
			{
				return screenReaderElements[label][ComModule.getLang().toLowerCase()];
			}
			else
			{
				return "";
			}
		}
	
	}
}